/*
 * @Author: leo
 * #19522 【混合】page混合
 */
import { Component, Vue, Watch } from "vue-property-decorator";
import { debounce, isArray, get } from "lodash";


@Component
export default class TableViewMix extends Vue {
  public data: any[] = []; // 当前页表格数据
  public limit = 10; // 每页大小
  public pageSizes: number[] = [5, this.limit, 20, 50, 100];
  public page = 1; // 当前页
  public total = 0;
  public query: any = {}; // 条件
  public loading = false; // 表格加载中
  public fetchDataAction: any;
  public isMounted = false; // 是否mounted
  private tableViewBodyHeight = 3000; // 表格最大高度

  public _mergeData(data1: any[], data2: any[]): any {
    return data1.map((item: any, index: number) => ({
      ...item,
      __auth__: (data2 && data2[index]) || {}
    }));
  }
  /**
   * fetch 数据
   */
  public async fetchData() {
    this.loading = true;
    // 拉取当前页数据
    let data = [];
    try {
      const {
        datas = [],
        buttonPermissions = [],
        total = 0
      } = await this.fetchDataAction(this.query, this.page, this.limit);
      this.data = data = this._mergeData(datas, buttonPermissions);
      this.total = total * 1;
    } catch (err) {
      console.log(err);
    }

    this.$nextTick(function() {
      this.loading = false;
    });
  }

  /**
   * 搜索
   */
  public handleSearch() {
    this.page = 1;
    this.fetchData();
  }

  // 更新页码
  public currentChange(pageNo: number) {
    this.page = pageNo;
    this.fetchData();
  }

  // 更改页面显示条数
  public sizeChange(count: number) {
    this.limit = count;
    this.fetchData();
  }

  public activated() {
    setTimeout(() => {
      this.isMounted = false;
    }, 0);
  }

  public mounted() {
    this.isMounted = true;
  }

  public filterChange(filter: any) {
    for (const key in filter) {
      if (this.query.hasOwnProperty(key)) {
        this.$set(
          this.query,
          key,
          isArray((this.query as any)[key]) ? get(filter, key, []) : get(filter, `${key}[0]`, "")
        );
      }
    }
    this.handleSearch();
  }

  // 列表select筛选条件变化自动搜索
  public searchSelectChange(val: string, key: string) {
    this.query[key] = val;
    this.$nextTick(() => {
      this.handleSearch();
    });
  }

  private bodyHeightChange(height: number) {
    this.tableViewBodyHeight = height - 41;
  }
}
